package com.suyang.syt.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/** 基于 httpclient 4.3.1版本的 http工具类 */
public class HttpTookit {
	private static final Logger logger = Logger.getLogger(HttpTookit.class);
	private static final CloseableHttpClient httpClient;
	private static final String CHARSET = "UTF-8";

	static {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	}

	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params, CHARSET);
	}

	public static String doPost(String url, Map<String, String> params) {
		return doPost(url, params, CHARSET);
	}

	/** HTTP Get 获取内容 */
	public static String doGet(String url, Map<String, String> params, String charset) {
		if (EmptyUtil.isEmpty(url)) {
			return null;
		}
		try {
			List<NameValuePair> pairs = setPairs(params);
			if (EmptyUtil.isNotEmpty(pairs)) {
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpGet.abort();
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/** 处理GET请求,返回文件输入流写入到file中 */
	public static void doGet(String url, Map<String, String> params, String charset, File file) {
		if (EmptyUtil.isEmpty(url)) {
			return;
		}
		try {
			List<NameValuePair> pairs = setPairs(params);
			if (EmptyUtil.isNotEmpty(pairs)) {
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpGet.abort();
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				FileUtils.copyInputStreamToFile(entity.getContent(), file);
			}
			response.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/** HTTP Post 获取内容 */
	public static String doPost(String url, Map<String, String> params, String charset) {
		if (EmptyUtil.isEmpty(url)) {
			return null;
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> pairs = setPairs(params);
			if (EmptyUtil.isNotEmpty(pairs)) {
				httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
			}
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpPost.abort();
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/** 将map内的参数转化类型 */
	private static List<NameValuePair> setPairs(Map<String, String> params) {
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String value = entry.getValue();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value));
				}
			}
			return pairs;
		}
		return null;
	}

	/** 处理字符串实体Post请求 */
	public static String doPostEntity(String url, String json, String contentType) {
		if (EmptyUtil.isEmpty(url)) {
			return null;
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content_Type", contentType);
			StringEntity stringEntity = new StringEntity(json, ContentType.create(contentType, CHARSET));
			httpPost.setEntity(stringEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpPost.abort();
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/** 处理文件实体Post请求 */
	public static String doPostFile(String url, String partName, String path) {
		if (EmptyUtil.isEmpty(url)) {
			return null;
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			FileBody fileBody = new FileBody(new File(path));
			HttpEntity httpEntity = MultipartEntityBuilder.create().addPart(partName, fileBody).build();
			httpPost.setEntity(httpEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpPost.abort();
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static String doPostFileEntity(String url, String pratFileName, String path, String partJsonName, String json, String contentType) {
		if (EmptyUtil.isEmpty(url)) {
			return null;
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			FileBody fileBody = new FileBody(new File(path));
			StringBody stringBody = new StringBody(json, ContentType.create(contentType, CHARSET));
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.addPart(pratFileName, fileBody);
			builder.addPart(partJsonName, stringBody);
			HttpEntity httpEntity = builder.build();
			httpPost.setEntity(httpEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				logger.error("HttpClient,error status code :" + statusCode);
				httpPost.abort();
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

}